// pages/post-detail/post-detail-service/post-detail-service.js
var util = require("../../../utils/util.js")
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    modalHidden: true,
    isLike: false,
    service_phone: '132-3305-8725',
    item: [{
      item_name: '美的不得了美甲',
      item_pic: '/[(@54ZNF`KHBTYVW1LAQN(G.png',
      actual_price: '180',
      all_price: '200'
    }, {
      item_name: '美的不得了美甲',
      item_pic: '/[(@54ZNF`KHBTYVW1LAQN(G.png',
      actual_price: '180',
      all_price: '200'
    }, ],
    bind_sum: 0,
    address: '',
    modal: true,
    text: "请选择服务人员后再预约下单,长按可以查看她们的详细信息哦~",
    marqueePace: 1, //滚动速度
    marqueeDistance: 0, //初始滚动距离
    marquee_margin: 50,
    size: 14,
    interval: 40, // 时间间隔
    dao: '',
    isxuan: false,
    service_name: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */


  touchEnd: function (e) {
    var that = this;
    that.setData({
      touchEnd: e.timeStamp
    })
  },
  dao: function (e) {
    console.log(e)
    this.setData({
      dao: e.currentTarget.dataset.value
    })
  },
  pressTap: function (e) {
    var postid = e.currentTarget.dataset.postid
    var that = this;
    var touchTime = that.data.touchStart - that.data.touchEnd;
    if (touchTime >= 600) { //自定义长按时长，单位为ms


      app.globalData.pass = this.data.item
      console.log(postid)
      that.setData({
        touchEnd: 0,
        touchStart: 0,
        ren_img: this.data.item[postid].service_img,
        ren_introduction: this.data.item[postid].self_introduction,
        ren_name: this.data.item[postid].service_name,
        modal: false
      })
    }
    if (touchTime < 600) {
      that.setData({
        touchEnd: 0,
        touchStart: 0
      })
    }
  },

  scrolltxt: function () {
    var that = this;
    var length = that.data.length; //滚动文字的宽度
    var windowWidth = that.data.windowWidth; //屏幕宽度
    if (length > windowWidth) {
      var interval = setInterval(function () {
        var maxscrollwidth = length + that.data.marquee_margin; //滚动的最大宽度，文字宽度+间距，如果需要一行文字滚完后再显示第二行可以修改marquee_margin值等于windowWidth即可
        var crentleft = that.data.marqueeDistance;
        if (crentleft < maxscrollwidth) { //判断是否滚动到最大宽度
          that.setData({
            marqueeDistance: crentleft + that.data.marqueePace
          })
        } else {
          //console.log("替换");
          that.setData({
            marqueeDistance: 0 // 直接重新滚动
          });
          clearInterval(interval);
          that.scrolltxt();
        }
      }, that.data.interval);
    } else {
      that.setData({
        marquee_margin: "1000"
      }); //只显示一条不滚动右边间距加大，防止重复显示
    }
  },

  onLoad: function (options) {

    console.log(options.id)
    //上门服务
    var that = this
    var item = []

    var service = app.globalData.service
    var service_sum = app.globalData.service_sum
    var service_items = app.globalData.service_items
    var service_items_sum = app.globalData.service_items_sum
    for (var i = 0; i < service_items_sum; i++) {
      if (service_items[i].item_name == options.id) {
        that.setData({
          service: service_items[i],
          isxianshang:service_items[i].isxianshang
        })
        if(service_items[i].isxianshang == 0){
          that.setData({
            dao:'到店服务'
          })
        }
      }
    }

    for (var j = 0; j < service_sum; j++) {
      for (var k = 0; that.data.service.service_name[k] != undefined; k++) {
        if (service[j].service_name = that.data.service.service_name[k]) {
          item.push(service[j])
        }
      }
    }
    console.log(item)
    that.setData({
      item: item
    })
    this.get()
    this.ons()
  },
  get() {
    var that = this
    var _this = this;
    var service = this.data.item
    for (var i = 0; i < that.data.item.length; i++) {
      service[i].distance = _this.getDistance(app.globalData.latitude, app.globalData.longitude, service[i].latitude, service[i].longitude) //查询用户与商家的距离
      console.log(_this.getDistance(app.globalData.latitude, app.globalData.longitude, service[i].latitude, service[i].longitude))
    }
    that.setData({
      item: service
    })
    // console.log(that.data.item[0].distance)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  like: function () {
    var that = this
    if (that.data.bind_sum <= 4) {
      if (this.data.isLike == false) {
        wx.showToast({
          title: '收藏成功',
          icon: 'success'
        })
        let tableName = 'love'
        let recordID = that.data.ID // 数据行 id
        let Product = new wx.BaaS.TableObject(tableName)
        let product = Product.getWithoutData(recordID)

        product.append('items', that.data.service.item_name) //在知晓云中列入邀请人
        product.update().then(res => {

        }, err => {
          // err
        })
      } else {
        wx.showToast({
          title: '取消成功',
          icon: 'success'
        })
        let tableName = 'love'
        let recordID = that.data.ID // 数据行 id
        let Product = new wx.BaaS.TableObject(tableName)
        let product = Product.getWithoutData(recordID)

        product.remove('items', that.data.service.item_name) //在知晓云中列入邀请人
        product.update().then(res => {

        }, err => {
          // err
        })
      }
      // console.log(wx.getStorageSync('isLike'))
      setTimeout(function (e) {
        that.setData({
          isLike: !that.data.isLike,
          bind_sum: that.data.bind_sum + 1
        })
      }, 200)

    } else {
      wx.showToast({
        title: '点击太快，请休息一会哦',
        icon: 'none'
      })
    }
  },
  ons() {
    var time = new Date();
    var year = time.getFullYear()
    var mouth = time.getMonth() + 1
    var day = time.getDate()
    var date = year + '-' + mouth + '-' + day
    console.log(date)
    if (wx.getStorageSync('service_kan_sum') != '') {
      var service = wx.getStorageSync('service_kan_sum')
      var index = 0
      for (var i = 0; i < service.length; i++) {
        if (service[i].service_code == this.data.service.item_name) {
          index = 1
          service[i].service_kan_sum = service[i].service_kan_sum + 1
          service[i].time.push(date)
          // service[i].k = 1
          wx.setStorageSync('k_', 1)
          wx.setStorageSync('service_kan_sum', service)
        }

      }
      if (index == 0) {
        var item = {
          service_code: this.data.service.item_name,
          service_kan_sum: 1,
          time: [date],
          id: this.data.service._id,
          // k:1
        }
        service.push(item)
        wx.setStorageSync('k_', 1)
        wx.setStorageSync('service_kan_sum', service)
      }
    } else {
      var item = {
        service_code: this.data.service.item_name,
        service_kan_sum: 1,
        time: [date],
        id: this.data.service._id,
        // k:1
      }
      console.log(index)
      wx.setStorageSync('service_kan_sum', [])
      var service = wx.getStorageSync('service_kan_sum')
      service.push(item)
      wx.setStorageSync('k_', 1)
      wx.setStorageSync('service_kan_sum', service)
      // wx.setStorageSync('product_kan_sum', )
    }
  },
  person: function (e) {
    console.log(e.currentTarget.dataset.postid)
    var id = e.currentTarget.dataset.postid
    this.setData({
      isxuan: true,
      idxxx: id,
      service_name: this.data.item[id].service_name
    })
    app.globalData.service_name = this.data.service_name
    // var k  = []
    // for(var i = 0 ; i < this.data.item.length ; i++){
    //   // this.data.item[i].isPoint = 1
    //   k.push(this.data.item[i])
    // }
    // console.log(k)
    // console.log(123)
    // var j = 0
    // while(j < this.data.item.length){
    //   if(j == id){
    //     console.log(1234)
    //     k[j].isPoint = 1
    //   }else{
    //     k[j].isPoint = 0
    //   }

    //   j++;
    // }
    // console.log(k)
    // this.setData({
    //   item:k
    // })
    // this.onA()
  },

  getDistance: function (lat1, lng1, lat2, lng2) {
    // lat1用户的纬度

    // lng1用户的经度

    // lat2商家的纬度

    // lng2商家的经度

    var radLat1 = this.Rad(lat1);

    var radLat2 = this.Rad(lat2);

    var a = radLat1 - radLat2;

    var b = this.Rad(lng1) - this.Rad(lng2);

    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));

    s = s * 6378.137;

    s = Math.round(s * 10000) / 10000;

    s = s.toFixed(2) //保留两位小数

    console.log('经纬度计算的距离:' + s)

    return s

  },
  Rad: function (d) { //根据经纬度判断距离

    return d * Math.PI / 180.0;

  },
  onShow: function (e) {
    var that = this;
    var length = that.data.text.length * that.data.size; //文字长度
    var windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕宽度
    //console.log(length,windowWidth);
    that.setData({
      length: length,
      windowWidth: windowWidth
    });
    console.log(2222)
    that.scrolltxt(); // 第一个字消失后立即从右边出现
    console.log(app.globalData.zhuzhiaddress)
    this.setData({
      address: app.globalData.zhuzhiaddress
    })
    var that = this
    var id = 0
    for (var i = 0; i < app.globalData.isLike.length; i++) {
      console.log(app.globalData.isLike[i])
      console.log(this.data.service.item_name)
      if (app.globalData.isLike[i] == this.data.service.item_name) {
        id = 1
      }
    }
    console.log(id)
    if (id == 1) {
      that.setData({
        isLike: true,
        ID: that.data.service.id
      })
    } else {
      let tableName = 'love'

      let Query = new wx.BaaS.Query()
      // Query.compare('product_code', '=', that.data.product_item.product_code)
      Query.compare('phone', '=', app.globalData.phone)
      let Product = new wx.BaaS.TableObject(tableName)
      Product.setQuery(Query).limit(1000).offset(0).find().then(res => {
        // success
        console.log(res.data.objects[0])
        for (var i = 0; i < res.data.objects[0].items.length; i++) {
          if (res.data.objects[0].items[i] == that.data.service.item_name) {
            that.setData({
              isLike: true,
              ID: res.data.objects[0].id
            })
          }
        }
        // console.log(res.data.objects[0].id)
        console.log(that.data.isLike)
        app.globalData.isLike.push(res.data.objects[0].items[0])
        console.log(app.globalData.isLike)
      }, err => {
        // err
      })
    }

  },
  yuyuedizhi: function (e) {
    if (this.data.address == '') {
      wx.navigateTo({
        url: '/pages/addresDetail/addresDetail?id=' + 1,
      })
    } else {
      wx.navigateTo({
        url: '/pages/addresDetail/addresDetail?id=' + 2,
      })
    }
  },
  lijiyuyue: function (e) {
    this.setData({
      modalHidden: false,
    })
  },
  modalCandel: function (e) {
    this.setData({
      modalHidden: true,
    })
  },
  modalConfirm:async function (e) {
    console.log(222)
    if (this.data.service_name == '') {
      wx.showToast({
        title: '未选择服务人员',
        icon: 'none'
      })
      this.setData({
        modalHidden: true,
      })
    } else if (this.data.address == '') {
      wx.showToast({
        title: '未选择预约地址',
        icon: 'none'
      })
      this.setData({
        modalHidden: true,
      })
    } else if (this.data.shijian == '') {
      wx.showToast({
        title: '未填写服务时间',
        icon: 'none'
      })
    } else if (this.data.isxianshang == 1 && this.data.dao == '') {
      wx.showToast({
        title: '未填写服务方式',
        icon: 'none'
      })
    } else {
      this.setData({
        modalHidden: true
      })
      var totalCost = parseInt(this.data.service.actual_price)
      var merchandiseSnapshot = {
        电话: app.globalData.phone,
        金额: this.data.service.actual_price,
        页面: '商品页',
        服务人员: this.data.service_name,
        服务时间: this.data.shijian,
        服务内容: this.data.service.item_name,
        服务方式: this.data.dao
      }

     
      var date = new Date();
      var mytime = date.toLocaleString();
      this.setData({
        date: mytime.toString()
      })
      await app.pay_service_items(totalCost, this.data.service.item_name + mytime, merchandiseSnapshot, this.data.service.id)

      var res = wx.getStorageSync('res')
      // app.globalData.isPay = true
      console.log(res)
      app.globalData.dingdanhao = res.transaction_no

      this.setOrder(res)
    }

  },
  setshijian: function (e) {
    console.log(e.detail.value)
    this.setData({
      shijian: e.detail.value
    })
  },
  GoitemDetail: function (e) {

    this.setData({
      modal: false
    })
  },
  modal_Confirm:  function (e) {
    this.setData({
      modal: true,
    })

  },
  modal_Candel: function (e) {
    this.setData({
      modal: true,
    })
  },
  setOrder(res) {
    console.log('set:111')
    var that = this
    if (wx.getStorageSync('res') != '') {
      console.log('set:222')
      let tableName = 'Order'
      let Product = new wx.BaaS.TableObject(tableName)
      let product = Product.create()
      var myDate = new Date();
      var mytime = myDate.toLocaleString();
      console.log(mytime)
      // 设置方式一
      // let apple = {
      //   name: that.data.product_name, //商品名称
      //   sum: that.data.modal_sum, //购买数量
      //   product_code: that.data.product_code_id, //产品编号
      //   phone: app.globalData.phone, //用户手机号
      //   transaction_no: app.globalData.dingdanhao, //流水号
      //   return_money: 1, //返利钱
      //   actual_price: that.data.modal_cost - '.00', //实际价格
      //   all_price: that.data.product_item.pre_cost, //原价
      //   payment_time: mytime //时间
      // }
      // console.log(that.data.modal_total.toString())
      // console.log(parseInt(that.data.modal_sum))
      // console.log(that.data.product_code_id.toString())
      // console.log(app.globalData.phone.toString())
      // console.log(res.transaction_no.toString())
      // console.log((that.data.modal_cost - '.00').toString())
      // console.log((that.data.product_item.pre_cost).toString())
      // console.log(mytime.toString())
      // console.log(that.data.address.toString())
      // if(that.data.)
      let apple = {
        name: that.data.service.item_name.toString(),
        service_name: app.globalData.service_name,
        phone: app.globalData.phone.toString(), //用户手机号
        transaction_no: res.transaction_no.toString(), //流水号
        actual_price: (that.data.service.actual_price).toString(), //实际价格
        all_price: (that.data.pservice.all_price).toString(), //原价
        payment_time: mytime.toString(), //时间
        address: that.data.address.toString(),
        fukuan: 1,
        service_time: that.data.shijian,
        isxianxia: that.data.dao
      }
      console.log(apple)
      product.set(apple).save().then(res => {
        // success
        console.log(res)
        setTimeout(function (e) {
          wx.redirectTo({
            url: '../post-detail/post-detail-buy/post-detail-buy?id=' + app.globalData.dingdanhao.toString(),
          })
        }, 500)
      }, err => {
        //err 为 HError 对象
        wx.showToast({
          title: '未成功创建订单',
        })
      })

    }
  },
})